package com.lz.exception;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.lz.model.ResultBean;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Package com.lz.exception
 * @Project currency-trading
 * @Author lenovo
 * @Date 2022/1/10 10:12
 * @Describe web层异常处理
 * @Version V1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 1、内部API调用的异常处理
     */
    @ExceptionHandler(value = ApiException.class)
    public ResultBean handlerApiException(ApiException exception) {
        IErrorCode errorCode = exception.getErrorCode();
        if (errorCode != null) {
            return ResultBean.fail(errorCode);
        }
        return ResultBean.fail(exception.getMessage());
    }

    /**
     * 2、方法参数校验失败的异常
     * MethodArgumentNotValidException
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultBean handlerMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return ResultBean.fail(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }
        return ResultBean.fail(exception.getMessage());
    }

    /**
     * 3、对象内部使用Validate 没有校验成功的异常
     */
    @ExceptionHandler(BindException.class)
    public ResultBean handlerBindException(BindException bindException) {
        BindingResult bindingResult = bindException.getBindingResult();
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                return ResultBean.fail(fieldError.getField() + fieldError.getDefaultMessage());
            }
        }
        return ResultBean.fail(bindException.getMessage());
    }

}

